package com.it.gw.modules.water.activity.sluice

import LoginVo
import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.it.common.Constants.REQUEST_CODE
import com.it.common.bean.MapDataBean
import com.it.common.utils.DisplayUtil
import com.it.common.utils.GsonUtils
import com.it.common.utils.RvSpacesItemUtils
import com.it.common.utils.isNotEmpty
import com.it.common.utils.tr
import com.it.data.manager.AppCacheManager
import com.it.data.network.req.SluiceRecordDto
import com.it.data.network.req.UploadFileDto
import com.it.gw.R
import com.it.gw.base.BaseActivity
import com.it.gw.data.PhotoBean
import com.it.gw.databinding.ActivitySluiceItemDetailBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.manager.DictionariesManager
import com.it.gw.manager.DictionariesManager.ENG_GRAD_1
import com.it.gw.manager.DictionariesManager.ENG_SCAL_1
import com.it.gw.modules.map.activity.MapActivity
import com.it.gw.modules.water.adapter.SelectPhotoAdapter
import com.it.gw.modules.water.viewmodel.WaterViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.io.File

//水闸详情
class SluiceItemDetailActivity : BaseActivity<ActivitySluiceItemDetailBinding>() {
    private val waterViewModel by viewModels<WaterViewModel>()
    private val photos = mutableListOf<PhotoBean>()
    private var selectPhotoAdapter: SelectPhotoAdapter? = null

    companion object {
        const val TAG = "SluiceItemDetailActivity"
    }


    override fun initObserver() {
        waterViewModel.sluiceRecordDtoDetailLiveData.observe(this) {
            ProgressDialog.hide()
            Log.d(TAG, "sluiceRecordDtoDetailLiveData: ${it}")
            if (it.result && it.data.isNotEmpty()) {
                setDetailView(it.data!!)
            }

        }
        waterViewModel.insertLiveData.observe(this) {
            ProgressDialog.hide()
            if (it.result) {
                Toast.makeText(this, "操作成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "${it.msg}", Toast.LENGTH_SHORT).show()
            }

        }

    }

    private fun setDetailView(data: SluiceRecordDto) {
        binding.lgtd.text = data.lgtd.tr()
        binding.lttd.text = data.lttd.tr()
        binding.wagaCode.setText(data.wagaCode.tr())
        binding.wagaName.setText(data.wagaName.tr())
        binding.sztcdm.setText(data.sztcdm.tr())
        binding.szhl.setText(data.szhl.tr())
        binding.szgq.setText(data.szgq.tr())


        binding.wagaUse.setText(data.wagaUse.tr())

        //工程等别
        binding.engGrad.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(ENG_GRAD_1),
                code = data.engGrad.tr()
            )
        )

//        binding.engGrad.setText(data.engGrad)

        //工程规模
        binding.engScal.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(ENG_SCAL_1),
                code = data.engScal.tr()
            )
        )

//        binding.engScal.setText(data.engScal)


        binding.lockDisc.setText(data.lockDisc.tr())
        binding.gaorNum.setText(data.gaorNum.tr())


        binding.gaorTotLen.setText(data.gaorTotLen.tr())
        binding.zmcc.setText(data.zmcc.tr())
        binding.zmxs.setText(data.zmxs.tr())
        binding.qbjts.setText(data.qbjts.tr())
        binding.qbjxs.setText(data.qbjxs.tr())

        binding.glfmj.setText(data.glfmj.tr())
        binding.kzggmj.setText(data.kzggmj.tr())
        binding.gldwmc.setText(data.gldwmc.tr())




        binding.note.setText(data.note.tr())

        binding.opinion.setText(data.opinion.tr())

        //显示文件图片
        if (data.fileList.isNotEmpty()) {
            val list =
                data.fileList?.map { PhotoBean(filePath = "", id = it.id, url = it.filePath) }
            photos.clear()
            if (list != null) {
                photos.addAll(list)
                selectPhotoAdapter?.notifyDataSetChanged()
            }
        }

    }


    override fun initListener() {
        binding.rlUpload.setOnClickListener {
            showPicSelect { type ->
                if (type == 1) {
                    takePhoto { path ->
                        Log.d(TAG, "onBindViewHolder: takePhoto ${it}")
                        uploadFile(path)

                    }
                } else if (type == 2) {
                    pickMedia { path ->
                        Log.d(TAG, "onBindViewHolder: pickMedia ${it}")
                        uploadFile(path)
                    }
                }

            }

        }
        binding.lgtd.setOnClickListener {
            startLocation()
        }
        binding.lttd.setOnClickListener {
            startLocation()
        }
        binding.gjsj.setOnClickListener {
            showDatePickerDialog(selectDateAction = {
                binding.gjsj.text = it
            })
        }
        binding.btnSave.setOnClickListener {
            sluiceApply()

        }
        binding.engGrad.setOnClickListener {
            DictionariesManager.dictionariesMap.get(ENG_GRAD_1)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.engGrad.text =
                            DictionariesManager.dictionariesMap.get(ENG_GRAD_1)!![index].ITEMNAME

                    })
            }
        }
        binding.engScal.setOnClickListener {
            DictionariesManager.dictionariesMap.get(ENG_SCAL_1)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.engScal.text =
                            DictionariesManager.dictionariesMap.get(ENG_SCAL_1)!![index].ITEMNAME

                    })
            }
        }
    }

    private fun uploadFile(path: String?) {
        lifecycleScope.launch {
            runCatching {
                ProgressDialog.show(this@SluiceItemDetailActivity)
                val uploadFileDtoList = mutableListOf<UploadFileDto>()
                val file = File(path)
                uploadFileDtoList.add(UploadFileDto(file = file, fileName = file.name))
                val res = waterViewModel.upload(uploadFileDtoList)
                ProgressDialog.hide()
                if (res.success == true) {
                    photos.add(PhotoBean(filePath = path, id = res.data))
                    selectPhotoAdapter?.notifyDataSetChanged()
                } else {
                    Toast.makeText(
                        this@SluiceItemDetailActivity,
                        "上传文件失败${res.message}",
                        Toast.LENGTH_LONG
                    ).show()
                }
            }.onFailure {
                ProgressDialog.hide()
                Toast.makeText(
                    this@SluiceItemDetailActivity,
                    "上传文件失败${it.message}",
                    Toast.LENGTH_LONG
                ).show()
            }
        }

    }

    //水闸增删改申请
    private fun sluiceApply() {
        ProgressDialog.show(this)

        val loginVo = MMKV.defaultMMKV()
            .decodeParcelable(AppCacheManager.KEY_LOGIN_DATA, LoginVo::class.java)
        val dto = SluiceRecordDto(
            lgtd = binding.lgtd.text.toString(),
            lttd = binding.lttd.text.toString(),
            wagaCode = binding.wagaCode.text.toString(),
            wagaName = binding.wagaName.text.toString(),
            sztcdm = binding.sztcdm.text.toString(),
            szhl = binding.szhl.text.toString(),
            szgq = binding.szgq.text.toString(),
            wagaUse = binding.wagaUse.text.toString(),
//            engGrad = binding.engGrad.text.toString(),
//            engScal = binding.engScal.text.toString(),
            engGrad = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(ENG_GRAD_1),
                name = binding.engGrad.text.toString()
            ),
            engScal = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(ENG_SCAL_1),
                name = binding.engScal.text.toString()
            ),
            lockDisc = binding.lockDisc.text.toString(),
            gaorNum = binding.gaorNum.text.toString(),
            gaorTotLen = binding.gaorTotLen.text.toString(),
            zmcc = binding.zmcc.text.toString(),
            zmxs = binding.zmxs.text.toString(),
            qbjts = binding.qbjts.text.toString(),
            qbjxs = binding.qbjxs.text.toString(),
            glfmj = binding.glfmj.text.toString(),
            kzggmj = binding.kzggmj.text.toString(),
            gldwmc = binding.gldwmc.text.toString(),
            note = binding.note.text.toString()
        )
        dto.state = "1"
        dto.type = dataType
        dto.inputAddvcd = loginVo?.depId
        dto.inputBy = loginVo?.id
        val picPath = photos.joinToString(",", transform = {
            it.id!!
        })
        dto.picPath = picPath

        waterViewModel.sluiceApply(dto)

    }

    override fun initData() {
        ProgressDialog.show(this)
        getData()
    }
    var dataType = "ADD"//数据操作类型
    private fun getData() {
        val operationType = intent.getStringExtra("operationType")
        val guid = intent.getStringExtra("guid")
        val type = intent.getStringExtra("type")
        val state = intent.getStringExtra("state")
        //审核详情
        if ("opinion" == operationType) {
            waterViewModel.getAfterSluiceParam(guid,type)
            if( state!!.contains("待")){
                binding.btnSave.visibility = View.GONE
                binding.llReason.visibility = View.GONE
                binding.rlUpload.isEnabled = false
                binding.rlUpload.setBackgroundColor(resources.getColor(R.color.color_B2B3BB))
                dataType = ""
            }
            else  if(state.contains("已")){
                binding.btnSave.visibility = View.GONE
                binding.llReason.visibility = View.GONE
                binding.rlUpload.isEnabled = false
                binding.rlUpload.setBackgroundColor(resources.getColor(R.color.color_B2B3BB))
                dataType = ""
            }
            else{
                dataType = "UPDATE"
                binding.btnSave.visibility = View.VISIBLE
                binding.llReason.visibility = View.VISIBLE
                binding.rlUpload.isEnabled = true
                binding.rlUpload.setBackgroundColor(resources.getColor(R.color.color_0F6AF8))
            }

        } else {
            dataType = "ADD"
            waterViewModel.getSluiceBasic(intent.getStringExtra("id")!!)
            binding.llReason.visibility = View.GONE
            binding.rlUpload.isEnabled = true
            binding.rlUpload.setBackgroundColor(resources.getColor(R.color.color_0F6AF8))

        }


    }


    var title = ""
    override fun initView() {
        DictionariesManager.getShuiZhaDictionaries()
        title = "${intent.getStringExtra("title")}"
        setTitle(
            title = title,
            isBack = true,
            tvRightRes1 = R.string.str_location,
            tvRight1Action = {
                val intent = Intent(this, MapActivity::class.java)
                intent.putExtra("title", title)
                val mapList = mutableListOf(
                    MapDataBean(
                        name = title,
                        lgtd = binding.lgtd.text.toString(),
                        lttd = binding.lttd.text.toString(),
                    )
                )
                intent.putExtra(MapActivity.MAP_DATA, GsonUtils.objToJsonStr(mapList))
                intent.putExtra("dataType",dataType)
                startActivityForResult(intent,REQUEST_CODE)
            }

        )
        initAdapter()

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==REQUEST_CODE){
            if(data!=null){
                val lgtd = data.getStringExtra("lgtd")
                val lttd = data.getStringExtra("lttd")
                binding.lgtd.text = lgtd
                binding.lttd.text = lttd

            }
        }
    }

    private fun initAdapter() {
        val map = hashMapOf(RvSpacesItemUtils.RIGHT_DECORATION to DisplayUtil.dip2px(this, 10f))
        binding.rvFile.addItemDecoration(RvSpacesItemUtils(map))



        binding.rvFile.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        selectPhotoAdapter = SelectPhotoAdapter(this, listener = {


        }, close = {
            photos.removeAt(it)
            selectPhotoAdapter?.notifyDataSetChanged()
        }, datas = photos)
        binding.rvFile.adapter = selectPhotoAdapter
    }


    override fun setContentView() {
        binding = ActivitySluiceItemDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }

    //声明AMapLocationClientOption对象
    private var mLocationOption: AMapLocationClientOption? = null

    //声明AMapLocationClient类对象
    private var mLocationClient: AMapLocationClient? = null
    private fun startLocation() {
        Log.d(TAG, "startLocation: ===========")
        mLocationClient = AMapLocationClient(applicationContext)
        mLocationClient?.setLocationListener(object : AMapLocationListener {
            override fun onLocationChanged(p0: AMapLocation?) {
                val longitude = "${p0?.longitude}"
                val latitude = "${p0?.latitude}"
                Log.d(TAG, "onLocationChanged: ${longitude} ${latitude}")
                binding.lttd.setText(latitude)
                binding.lgtd.setText(longitude)

            }

        })

        mLocationOption = AMapLocationClientOption()
        val option = AMapLocationClientOption()
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn)
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        option.setOnceLocationLatest(true);

        if (null != mLocationClient) {
            mLocationClient?.setLocationOption(option)
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient?.stopLocation()
            mLocationClient?.startLocation()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient?.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }


}